package com.polaris.live.popup

import android.content.Context
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.StringUtils
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.adapter.SetLanguageAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupSetLanguageBinding
import com.polaris.live.manager.AssetsConfigManager
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.LanguageResp
import com.polaris.live.resp.go_resp.InfoModifyBean
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 语言选择
 * isTranslation是获取同声传译的json
 * @author Created by 半仙 on 2023/9/27/027 17:45
 */
class SetLanguagePopup(
    context: Context,
    private val mOnSelectLanguage: ((data: LanguageResp?) -> Unit),
    private val mViewModel: BaseViewModel,
    private val mIsTranslation: Boolean = false,
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupSetLanguageBinding
    private val mAdapter by lazy { SetLanguageAdapter() }

    private var mSelectIndex = -1
    private var mLanguage = ""

    override fun getImplLayoutId(): Int {
        return R.layout.popup_set_language
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupSetLanguageBinding.bind(popupImplView)

        if (UserManager.getUser().profile?.secondLanguage.isNullOrEmpty()) {
            mBinding.systemLanguage.text =
                StringUtils.getString(string.not_set)
        } else {
            mBinding.systemLanguage.text =
                UserManager.getUser().profile?.secondLanguage?.let {
                    CommonUtils.getLanguageNameFromCode(it)
                }
        }

        val flexBoxLayout = FlexboxLayoutManager(context)
        flexBoxLayout.flexDirection = FlexDirection.ROW
        flexBoxLayout.justifyContent = JustifyContent.FLEX_START
        flexBoxLayout.flexWrap = FlexWrap.WRAP

        mBinding.recycler.apply {
            adapter = mAdapter
            layoutManager = flexBoxLayout
        }

        initListener()
        if (mIsTranslation) {
            mViewModel.viewModelScope.launch {
                val data = AssetsConfigManager.readTranslation()
                withContext(CoroutineScopeManager.mainDispatcher) {
                    val speechLanguage = UserManager.getUser().profile?.spokenLanguage
                    if (!speechLanguage.isNullOrEmpty()) {
                        data.forEach {
                            if (it.code == speechLanguage) {
                                mBinding.systemLanguage.text = "${it.language}-${it.country}"
                            }
                        }
                    } else {
                        mBinding.systemLanguage.text = StringUtils.getString(string.not_set)
                    }
                    data.forEach {
                        mAdapter.addData(LanguageResp("", "${it.language}-${it.country}", it.code))
                    }
                }
            }
        } else {
            mViewModel.viewModelScope.launch {
                val data = AssetsConfigManager.fetchLanguage()
                withContext(CoroutineScopeManager.mainDispatcher) {
                    mAdapter.setList(data)
                }
            }
        }
    }

    private fun initListener() {
        mAdapter.setOnItemClickListener { _, _, position ->
            mAdapter.clearSelected()

            mAdapter.setSelect(position)
            mSelectIndex = position
        }

        mBinding.saveLanguage.setOnSingleClickListener {
            if (mSelectIndex == -1) {
                ToastGravity.showGravity(context.getString(string.unselected_language))
                return@setOnSingleClickListener
            }

            if (mIsTranslation) {
                mOnSelectLanguage.invoke(mAdapter.data[mSelectIndex])
                dismiss()
                return@setOnSingleClickListener
            }

            val language = mAdapter.getItemOrNull(mSelectIndex) ?: return@setOnSingleClickListener
            if (language.language.isEmpty()) return@setOnSingleClickListener
            mLanguage = language.language

            mViewModel.requestLoading(
                { userService.infoModify(InfoModifyBean(secondLanguage = mLanguage)) },
                {
                    if (mSelectIndex == -1) {
                        mOnSelectLanguage.invoke(null)
                    } else {
                        mOnSelectLanguage.invoke(mAdapter.data[mSelectIndex])
                    }
                    dismiss()
                },
                {
                    ToastGravity.showGravity(it.errorMsg)
                })
        }
    }
}